package com.example.core.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


/**
 * @Author: cc
 * @since: 2020/9/22 0022 10:53
 */
@Slf4j
public class Httputil {
    private static final String CONTENT_TYPE_KEY = "Content-Type";
    private static final String DEFAULT_CHARSET = "UTF-8";

    private Httputil() {
        //
    }

    public static JSONObject sendHttpGet(String url, Map<String, Object> params, Map<String, Object> headerMap) throws IOException {
        //创建 返回实体类
        JSONObject jso = null;
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.createDefault();
            URIBuilder uriBuilder = new URIBuilder(url);
            //解析传值 参数
            List<NameValuePair> paraList = new LinkedList<>();
            if (params != null) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    BasicNameValuePair param1 = new BasicNameValuePair
                            (entry.getKey(), entry.getValue() == null ? "" : entry.getValue() + "");
                    paraList.add(param1);
                }
            }
            //添加参数的形式
            uriBuilder.addParameters(paraList);
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");

            //添加 自定义 Header 消息头
            if (headerMap != null && headerMap.size() > 0) {
                for (Map.Entry<String, Object> entry : headerMap.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue() + "");
                }
            }
            if (headerMap != null && !headerMap.containsKey(CONTENT_TYPE_KEY)) {
                httpGet.addHeader(CONTENT_TYPE_KEY, "application/json;charset=utf-8");
            }
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {

                // 获得响应的实体对象
                HttpEntity entity = response.getEntity();
                // 使用Apache提供的工具类进行转换成字符串
                String entityStr = EntityUtils.toString(entity, DEFAULT_CHARSET);
                jso = JSONObject.parseObject(entityStr);
            }
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return jso;
    }

    public static JSONObject sendHttpPost(String url, JSONObject jso, Map<String, Object> headerMap) {

        //创建 返回实体类
        JSONObject result = null;
        try (DefaultHttpClient httpclient = new DefaultHttpClient()) {
            httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30 * 1000);

            HttpPost httppost = new HttpPost(url);
            httppost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            httppost.addHeader(CONTENT_TYPE_KEY, "application/json;charset=utf-8");
            //添加 自定义 Header 消息头
            if (headerMap != null && headerMap.size() > 0) {
                for (Map.Entry<String, Object> entry : headerMap.entrySet()) {
                    httppost.addHeader(entry.getKey(), entry.getValue() + "");
                }
            }
            StringEntity entity = new StringEntity(jso.toString(), Charset.forName(DEFAULT_CHARSET));
            entity.setContentEncoding(DEFAULT_CHARSET);
            httppost.setEntity(entity);

            HttpResponse resp = httpclient.execute(httppost);
            if (resp.getStatusLine().getStatusCode() == 200) {
                HttpEntity he = resp.getEntity();
                String respContent = EntityUtils.toString(he, DEFAULT_CHARSET);
                result = JSONObject.parseObject(respContent);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return result;
    }
}
